//
//  detailNewViewController.m
//  ZhihunewPaper
//
//  Created by 梅杰 on 16/7/16.
//  Copyright © 2016年 梅杰. All rights reserved.
//

#import "detailNewViewController.h"
#import "DetailNew.h"
#import "HttpsManager.h"
#import "UIImageView+WebCache.h"
#import "BottomBar.h"
#import "Extra.h"

#define KimageHeight 200 //图片初始显示出来的高度，不是真实高度
#define TitleLabelFont [UIFont fontWithName:@"ArialHebrew-Bold" size:21]
#define titleLabelSize [self heightForNsstring:self.titleLabel.text maxWidth:KScreenWidth - 10 font:TitleLabelFont]
#define toolBarHeight 45
#define LeftMargin 100 //上一篇，下一篇控件左右边距
#define MidMargin 10 //上一篇和下一篇中imageview和label间的边距
#define TopMargin 60 //上一篇控件**上边距
#define BottomMargin 40 //下一篇控件**下边距
@interface detailNewViewController () <UIScrollViewDelegate>
@property (nonatomic,weak)UIWebView *webView;
@property (nonatomic,assign) Boolean showStatusView;
@property (nonatomic,strong) DetailNew *aNew;
@property (nonatomic,weak) UIImageView *headImageView;
@property (nonatomic,weak) UIView *statusView;
@property (nonatomic,assign) CGRect imagViewRect;

@property (nonatomic,weak) UIImageView *lastPassImage;
@property (nonatomic,weak) UIImageView *nextPassImage;
@property (nonatomic,weak) UILabel *lastPassLabel;
@property (nonatomic,weak) UILabel *nextPassLabel;
@property (nonatomic,weak) UILabel *titleLabel;

@property (nonatomic,strong) Extra *aExtra;
@property (nonatomic,weak) BottomBar *bottomBar;
//@property (nonatomic,weak) UILabel *testlabel;
@end

@implementation detailNewViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    // Do any additional setup after loading the view.
    [self initAllWeight];
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSString *newID = appDelegate.newsID;
//    NSLog(@"%@",appDelegate.newsIDArray);
//    NSLog(@"%@",[NSString stringWithUTF8String:object_getClassName(appDelegate.newsIDArray.firstObject)]);
    
    [self aNewWithNetRequest:[self getRequestUrl:newID]];
    
    [self getExtraFromRequest:[self getExtraUrl:newID]];
    
    [self backToPresentingVC];
}
//侧滑方法，使其支持侧滑返回
- (void) backToPresentingVC{
    UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(backSwipeGesture)];
    rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:rightSwipe];
}
- (void) backSwipeGesture{
//    NSLog(@"支持侧滑");
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void) initAllWeight {
    
    UIWebView *webview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-toolBarHeight)];
//    [self.webView loadHTMLString:[NSString stringWithFormat:@"<html><head><link rel=\"stylesheet\" href=%@></head><body>%@</body></html>",self.aNew.css[0],self.aNew.body] baseURL:nil];
    [self.view addSubview:webview];
    self.webView = webview;
    webview.scrollView.delegate = self;
    webview.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(KimageHeight, 0, 0, 0);
    
    UIView *statusView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,KScreenWidth , 20)];
    statusView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:statusView];
    statusView.hidden = YES;
    self.statusView = statusView;
    
//    self.webView.scrollView.backgroundColor = [UIColor redColor];
    
    self.webView.scrollView.backgroundColor = [UIColor clearColor];
    self.webView.scrollView.bouncesZoom = NO;
//    self.webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, KScreenWidth - KimageHeight,0);
    self.webView.backgroundColor = [UIColor whiteColor];

    //一个imageView，显示图片
    UIImageView *headView = [[UIImageView alloc] init];
    headView.frame = CGRectMake(0, KimageHeight - KScreenWidth, KScreenWidth, KScreenWidth);
    [self.webView.scrollView addSubview:headView];
    self.headImageView = headView;
//    self.imagViewRect = headView.frame;
//    headView.backgroundColor = [UIColor redColor];
    
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.numberOfLines = 0;
    [headView addSubview:titleLabel];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = TitleLabelFont;
    self.titleLabel = titleLabel;
//    NSString *title = titleLabel.text;
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(headView);
        make.bottom.equalTo(headView).offset(-15);
        make.height.mas_equalTo(titleLabelSize.height + 5);
        make.width.mas_equalTo(titleLabelSize.width);
//        make.size.mas_equalTo(titleSize);
    }];
    [titleLabel layoutIfNeeded];
//    CGSize ss = titleLabel.frame.size;
    
    BottomBar *bottomBar = [[NSBundle mainBundle] loadNibNamed:@"BottomBar" owner:nil options:nil].firstObject;
    self.bottomBar = bottomBar;
    [self.view addSubview:bottomBar];
    __weak typeof(self) __wakeme = self;
    [bottomBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(__wakeme.view);
        make.leading.equalTo(__wakeme.view);
        make.trailing.equalTo(__wakeme.view);
        make.height.mas_equalTo(toolBarHeight);
    }];
    [bottomBar setWeightMethodForArrow:^(UIButton *sender) {
        NSLog(@"返回");
        
        [self dismissViewControllerAnimated:YES completion:nil];
    } nextBlock:^(UIButton *sender) {
        NSLog(@"下一个");
        [self getNextNew];
    } voteBlock:^(UIButton *sender) {
        NSLog(@"投票");
    } shareBlock:^(UIButton *sender) {
        NSLog(@"分享");
    } commentBlock:^(UIButton *sender) {
        NSLog(@"评论");
    }];
//    [scrollView addSubview:headView];
    
    //下面是上拉Label和下拉Label
    UILabel *lastPass = [[UILabel alloc] init];
    lastPass.text = @"载入上一篇";
    lastPass.textColor = [UIColor lightTextColor];
    UILabel *nextPass = [[UILabel alloc] init];
    nextPass.text = @"载入下一篇";
    nextPass.textColor = [UIColor lightGrayColor];
    UIImage *lastImage = [UIImage imageNamed:@"ZHAnswerViewBackIcon"];
    UIImage *nextImage = [UIImage imageNamed:@"ZHAnswerViewPrevIcon"];
    UIImageView *lastImageView = [[UIImageView alloc] initWithImage:lastImage];
    UIImageView *nextImageView = [[UIImageView alloc] initWithImage:nextImage];
    self.lastPassImage = lastImageView;
    self.nextPassImage = nextImageView;
    self.lastPassLabel = lastPass;
    self.nextPassLabel = nextPass;
    
    [self.webView.scrollView addSubview:lastPass];
    [self.webView.scrollView addSubview:lastImageView];
    [self.webView insertSubview:nextImageView belowSubview:self.webView.scrollView];
    [self.webView insertSubview:nextPass belowSubview:self.webView.scrollView];
    
    __weak typeof(UIWebView *) __wakeWeb = self.webView;
    [lastImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headView).offset(TopMargin);
        make.size.mas_equalTo(lastImage.size);
        make.leading.equalTo(headView).offset(LeftMargin);
    }];
    
    [lastPass mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headView).offset(TopMargin);
        make.trailing.equalTo(headView).offset(-LeftMargin);
        make.height.equalTo(lastImageView.mas_height);
        make.leading.equalTo(lastImageView.mas_trailing).offset(MidMargin);
    }];
    [self.webView.scrollView bringSubviewToFront:lastPass];
//    lastImageView.backgroundColor = [UIColor redColor];
//    lastPass.backgroundColor = [UIColor redColor];
    
    [nextImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(__wakeWeb.scrollView.mas_bottom).offset(-BottomMargin);
        make.size.mas_equalTo(lastImage.size);
        make.leading.equalTo(__wakeWeb).offset(LeftMargin);
    }];
    [nextImageView layoutIfNeeded];
//    NSLog(@"%@",NSStringFromCGRect(nextImageView.frame));
//    NSLog(@"%@",NSStringFromCGRect(self.webView.scrollView.frame));
    [nextPass mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(__wakeWeb.mas_bottom).offset(-BottomMargin);
        make.trailing.equalTo(__wakeWeb).offset(-LeftMargin);
        make.height.equalTo(lastImageView.mas_height);
        make.leading.equalTo(lastImageView.mas_trailing).offset(MidMargin);
    }];

}
- (CGSize )heightForNsstring : (NSString *)title maxWidth : (CGFloat)maxWidth font:(UIFont *) font{
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil];
    
    CGSize size = [title boundingRectWithSize:CGSizeMake(maxWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    
    return size;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark scrollview的相关办法

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint offset = scrollView.contentOffset;
    CGSize contentSize = scrollView.contentSize;
    
    UIImage *lastImage = [UIImage imageNamed:@"ZHAnswerViewBackIcon"];
    UIImage *nextImage = [UIImage imageNamed:@"ZHAnswerViewPrevIcon"];
//    NSLog(@"图片尺寸%@",NSStringFromCGRect
//          (self.headImageView.frame));
    NSLog(@"偏移%f",offset.y);
//    NSLog(@"%f %f",offset.y , KimageHeight - KScreenWidth);
    if (_webView.scrollView.contentOffset.y > KimageHeight) {
//        [self.navigationController.navigationBar setBarTintColor:[UIColor redColor]];
        [self setNeedsStatusBarAppearanceUpdate];
        self.statusView.hidden = NO;
    }else{
         self.statusView.hidden = YES;
        [self setNeedsStatusBarAppearanceUpdate];
    }
    
    
    //控制滑到顶部不能再滑到
    if (offset.y < -(KScreenWidth - KimageHeight) ) {
        self.webView.scrollView.contentOffset = CGPointMake(0, KimageHeight - KScreenWidth);
    }
    if (offset.y < KimageHeight - KScreenWidth + 25) {
        
        self.lastPassImage.image = nextImage;
    }else{
        
        self.lastPassImage.image = lastImage;
    }
    
    if (KScreenHeight + offset.y - contentSize.height > BottomMargin + 90) {
        
        self.nextPassImage.image = lastImage;
        
    }else{
        
        self.nextPassImage.image = nextImage;
        
    }
//    NSLog(@"测试滑动%@",NSStringFromCGRect(self.testlabel.frame));
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    CGPoint offset = scrollView.contentOffset;
    CGSize contentSize = scrollView.contentSize;
    
    if (self.webView.scrollView.contentOffset.y < KimageHeight - KScreenWidth + 25) {
        [self getLastNew];
    }
    if (KScreenHeight + offset.y - contentSize.height > BottomMargin + 90){
        [self getNextNew];
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    if (_webView.scrollView.contentOffset.y > KimageHeight) {
        return UIStatusBarStyleDefault;
//        return UIStatusBarStyleBlackTranslucent;
    }
    return UIStatusBarStyleLightContent;
}

#pragma mark 请求网络形成一个new的实例
- (void) aNewWithNetRequest : (NSString *) url{
    
    [HttpsManager getUrlDataWithUrl:url Param:nil Success:^(NSDictionary * _Nonnull dict, Boolean flag) {
//        NSLog(@"这是字典内容%@",dict);
        DetailNew *new = [[DetailNew alloc] initWithDictionary:dict error:nil];
        self.aNew = new;
//        NSLog(@"%@",new);
//        [webview loadHTMLString:[NSString stringWithFormat:@"<html><head><link rel=\"stylesheet\" href=%@></head><body>%@</body></html>",new.css[0],new.body] baseURL:nil];
//        self.webView = webview;
//        //        webview.delegate = self;
//        webview.scrollView.delegate = self;
//        webview.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(KimageHeight, 0, 0, 0);
        //        self.webView.userInteractionEnabled = NO;
//        [self initAllWeight];
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"网络请求失败");
    }];
    
//    return nil;
}
#pragma mark 返回请求url
- (NSString *) getRequestUrl : (NSString *) newsID{
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"interface" ofType:@"plist"]];
    NSString *baseUrl = dict[@"baseUrl"];
    NSString *url = [NSString stringWithFormat:@"%@/%@",baseUrl,newsID];
    return url;
}

- (void)setANew:(DetailNew *)aNew{
    _aNew = aNew;
    [self.headImageView sd_setImageWithURL:self.aNew.image placeholderImage:[UIImage imageNamed:@"loadImageFailed"]];

    [self.webView loadHTMLString:[NSString stringWithFormat:@"<html><head><link rel=\"stylesheet\" href=%@></head><body>%@</body></html>",self.aNew.css[0],self.aNew.body] baseURL:nil];
    
    self.titleLabel.text = self.aNew.title;
//    [self.titleLabel setBackgroundColor:[UIColor redColor]];
    
    [self.view setNeedsUpdateConstraints];
    [self.view updateConstraintsIfNeeded];
    [self.view layoutIfNeeded];
    
}

- (void)updateViewConstraints {
    [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(titleLabelSize.height + 5);
        make.width.mas_equalTo(titleLabelSize.width);
    }];
    //最后记得回调super方法
    
    
    [super updateViewConstraints];
}
//- (void) initAllObserver{
//    
//}

//下一篇
- (void) getNextNew{
    
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSString* newsID = appDelegate.newsID;
    NSArray *newsIDArray = appDelegate.newsIDArray;
    NSInteger index = [newsIDArray indexOfObject:newsID];
    if ( newsID != newsIDArray.lastObject) {
        NSString * nextID = ((NSString *)[newsIDArray objectAtIndex:++index]);
        NSString *nextUrl = [self getRequestUrl:nextID];
        [self aNewWithNetRequest:nextUrl];
        appDelegate.newsID = nextID;
        [self getExtraFromRequest:[self getExtraUrl:newsID]];
    }else{
        self.nextPassLabel.text = @"已是最后一篇";
    }
//    NSString *nextID = [newsIDArray obj];
}
//上一篇
- (void) getLastNew{
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSString * newsID = appDelegate.newsID;
    NSArray *newsIDArray = appDelegate.newsIDArray;
    NSLog(@"%@",newsIDArray);
    NSInteger index = [newsIDArray indexOfObject:newsID];
    if (newsID != newsIDArray.firstObject) {
        NSString * lastID = ((NSString *)[newsIDArray objectAtIndex:--index]);
        NSString *lastUrl = [self getRequestUrl:lastID];
        [self aNewWithNetRequest:lastUrl];
        appDelegate.newsID = lastID;
        
        [self getExtraFromRequest:[self getExtraUrl:lastID]];
    }else{
        self.lastPassLabel.text = @"已是第一篇";
    }
}

#pragma mark 得到评论等东西（extra）

- (void) getExtraFromRequest : (NSString *)url{
    [HttpsManager getUrlDataWithUrl:url Param:nil Success:^(NSDictionary * _Nonnull dict, Boolean flag) {
                NSLog(@"这是字典内容%@",dict);
        NSDictionary *countDict = dict[@"count"];
        Extra *aExtra = [[Extra alloc] initWithDictionary:countDict error:nil];
        self.aExtra = aExtra;

    } fail:^(NSError * _Nonnull error) {
        NSLog(@"extra网络请求失败");
    }];
}
- (NSString *)getExtraUrl : (NSString *)newsID {
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"interface" ofType:@"plist"]];
    NSString *baseUrl = dict[@"story-extra"];
    NSString *url = [NSString stringWithFormat:@"%@/%@",baseUrl,newsID];
    return url;
}
- (void)setAExtra:(Extra *)aExtra{
    _aExtra = aExtra;
    BottomBar *theBottonBar = self.bottomBar;
    [theBottonBar.voteButton setTitle:[NSString stringWithFormat:@"%ld",aExtra.likes] forState:UIControlStateNormal];
    [theBottonBar.commentButton setTitle:[NSString stringWithFormat:@"%ld",aExtra.comments] forState:UIControlStateNormal];
//    theBottonBar.
}
//实现kvo方法
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
